#include <iostream>
#include <ctime>
#include <algorithm>
#include <cstdlib>
#include "SimplePlayer.h"

using namespace std;

SimplePlayer::SimplePlayer(string name) :
		Player(name) {
}

Cell* SimplePlayer::next() {
	vector<Cell*> cells = *(mBoard->findPutableCells(mColor));
	if (cells.empty()) {
		return NULL;
	} else if (cells.size() == 1) {
		return cells[0];
	}

	vector<CandidateCell*> candidateCells;

	vector<Cell*>::iterator itCells = cells.begin();
	while (itCells != cells.end()) {
		Cell* cell = (*itCells);
		CandidateCell* candidateCell = new CandidateCell(mColor, mBoard, cell);
		if (!candidateCell->isWideMarginWon(Stone::otherColor(mColor))) {
			candidateCells.push_back(candidateCell);
		}
		++itCells;
	}

	if (candidateCells.empty()) {
		return cells[0];
	}

	sort(candidateCells.begin(), candidateCells.end(), &CandidateCell::cmp);

	Cell* retCell = mBoard->getCell(candidateCells[0]->mCell->getX(), candidateCells[0]->mCell->getY());
	clear(candidateCells);

	return retCell;
}

void SimplePlayer::clear(vector<CandidateCell*> cells) {
	vector<CandidateCell*>::iterator it = cells.begin();
	while (it != cells.end()) {
		CandidateCell* cell = (*it);
		delete cell;
		++it;
	}
}
